package com.ggkt.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Type;


/**
 * <p>
 * json处理工具类
 * </p>
 * 
 * @author ggkt
 */
@Slf4j
public class JsonUtil {
    
    private static Gson gsonInstance = null;

	/**
	 * 将对象转为json格式的字符串
	 */
	public static String object2JsonStr(Object object) {
		
		return object == null ? null : getGson().toJson(object);
	}

	/**
	 *  将json字符串转为相应对象
	 * 
	 * @param jsonStr
	 * @param clazz
	 */
	public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) {
		try{
		 return StringUtils.isNotBlank(jsonStr) ? getGson().fromJson(jsonStr,
				clazz) : null;
		}catch (Exception e) {
			log.error("jsonStr2Object error!", e);
		}
		
		return null;
		 
	}
	
	/**
	 * 
	 * 将json字符串转为相应对象,举例：
	 * 
	 * <code>
	 * 		List<CwareVideo> videoList = ParameterUtil.jsonStr2Object(videoListJsonStr, new TypeToken<ArrayList<CwareVideo>>(){}.getType());
	 * </code>
	 * 
	 * @param jsonStr
	 * @param type
	 */
	@SuppressWarnings("unchecked")
	public static <T> T jsonStr2Object(String jsonStr, Type type) {
		return (T) (StringUtils.isNotBlank(jsonStr) ? getGson().fromJson(jsonStr, type) : null);
	}
	
	private static Gson getGson(){
	    if (gsonInstance == null) {
	        gsonInstance = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").setPrettyPrinting().disableHtmlEscaping().create();
	    }
		return gsonInstance;
	}
	
	public static void main(String[] args) {
		System.out.println(45566);
	}

}
